<template>
  <div>
    <SearchForm @search="getTableData" @reset="resetSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[1511]">
        <el-form-item :label="$t('所属租户')">
          <el-select
              style="width: 100%"
              v-model="page.adminUserId"
              clearable
          >
            <el-option
                v-for="item in tenantList"
                :key="item.adminUserId"
                :label="item.adminName"
                :value="item.adminUserId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('优惠券名称')" label-width="100px">
          <el-input v-model="page.name"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('优惠券类型')" label-width="100px">
          <el-select style="width: 100%" v-model="page.type" clearable>
            <el-option v-for="item in couponType" :value="item.value" :key="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('获取方式')">
          <el-select style="width: 100%" v-model="page.getType" clearable>
            <el-option v-for="item in couponGetType" :value="item.value" :key="item.value"
                       :label="item.label"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('状态')">
          <el-select style="width: 100%" v-model="page.activityStatus">
            <el-option :value="1" :label="$t('未过期')"></el-option>
            <el-option :value="2" :label="$t('已过期')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('上架状态')">
          <el-select style="width: 100%" v-model="page.upType">
            <el-option :value="0" :label="$t('待上架')"></el-option>
            <el-option :value="1" :label="$t('已上架')"></el-option>
            <el-option :value="2" :label="$t('已下架')"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('创建时间')">
          <el-date-picker
              v-model="page.timeValue"
              style="width: 100%"
              type="daterange"
              value-format="yyyy-MM-dd"
              unlink-panels
              range-separator="~"
              :start-placeholder="$t('开始日期')"
              :end-placeholder="$t('结束日期')">
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card shadow="never" style="margin-top: 10px">
      <div style="margin-bottom:10px;text-align: right">
        <el-button type="primary" @click="addCoupon" v-show="$permiss[1492]">{{ $t('新增优惠券') }}</el-button>
      </div>
      <Table :table-data="tableData" :table-column="tableColumn" :page="page" @handleSizeChange="handleSizeChange"
             @handleCurrentChange="handleCurrentChange">
        <template slot="type" slot-scope="{row}">
          {{ couponType.find(item => item.value === row.type).label }}
        </template>
        <template slot="sendUser" slot-scope="{row}">
          {{ sendSmsType.find(item => item.value === row.sendUser).label }}
        </template>
        <template slot="amount" slot-scope="{row}">
          {{ row.amount }}<span v-show="row.amountType === 2">%</span>
        </template>
        <template slot="sendApp" slot-scope="{row}">
          {{ row.sendApp === 1 ? $t('全部APP') : row.sendApp === 2 ? $t('指定APP') : $t('指定类型') }}
        </template>
        <template slot="getType" slot-scope="{row}">
          {{ couponGetType.find(item => item.value === row.getType).label }}
        </template>
        <template slot="sendSms" slot-scope="{row}">
          {{ row.sendSms === 1 ? $t('是') : $t('否') }}
        </template>
        <template slot="activityTime" slot-scope="{row}">
          {{ row.activityStartTime }} - {{ row.activityEndTime }}
        </template>
        <template slot="activityStatus" slot-scope="{row}">
          {{ row.activityStatus === 1 ? $t('未过期') : $t('已过期') }}
        </template>
        <template slot="upType" slot-scope="{row}">
          {{ row.upType === 0 ? $t('待上架') : row.upType === 1 ? $t('已上架') : $t('已下架') }}
        </template>
        <template slot="handle" slot-scope="{row}">
          <el-button type="text" @click="lookDetails(row)">{{ $t('查看') }}</el-button>
          <el-button type="text" v-show="$permiss[1494] && row.upType !== 1" @click="editCoupon(row)">{{
              $t('编辑')
            }}
          </el-button>
          <el-button type="text" v-show="$permiss[1494] && row.activityStatus === 1" @click="editUpper(row)">
            {{ row.upType === 0 || row.upType === 2 ? $t('上架') : $t('下架') }}
          </el-button>
          <el-button type="text" @click="getCouponDetails(row)">{{ $t('明细') }}</el-button>
        </template>
      </Table>
    </el-card>
    <!-- 新增优惠券-->
    <Dialog :visible.sync="couponVisible.isShow" :title="couponVisible.title" @confirm="couponConfirm"
            @cancel="couponVisible.isShow = false" @close="couponClose" width="40%"
            :footer="couponVisible.type !== 'details'">
      <AddCoupon ref="couponModel" :visible="couponVisible" :rows="tableRows"/>
    </Dialog>


    <!--    优惠券明细-->
    <Dialog :visible.sync="visibleDetails" :title="$t('优惠券明细')" width="65%" :footer="false">
      <div style="margin-bottom: 15px">
        <h3 style="margin:0 0 15px 0">{{ $t('优惠券基本信息') }}</h3>
        <Table border :tableColumn="detailsTableColumn" :tableData="detailsTableData" :page="false">
          <template slot="amount" slot-scope="{row}">
            {{ row.amount }}<span v-show="row.amountType === 2">%</span>
          </template>
          <template slot="type" slot-scope="{row}">
            {{ couponType.find(item => item.value === row.type).label }}
          </template>
          <template slot="sendUser" slot-scope="{row}">
            {{ sendSmsType.find(item => item.value === row.sendUser).label }}
          </template>
          <template slot="sendApp" slot-scope="{row}">
            {{ row.sendApp === 1 ? $t('全部APP') : row.sendApp === 2 ? $t('指定APP') : $t('指定类型') }}
          </template>
          <template slot="getType" slot-scope="{row}">
            {{ couponGetType.find(item => item.value === row.getType).label }}
          </template>
          <template slot="activityStatus" slot-scope="{row}">
            {{ row.activityStatus === 1 ? $t('未过期') : $t('已过期') }}
          </template>
        </Table>
      </div>
      <div>
        <h3 style="margin:0 ">{{ $t('优惠券消耗数据') }}</h3>
        <el-row :gutter="24" style="margin: 15px 0  ">
          <el-form label-width="80px">
            <el-col :span="6">
              <el-form-item :label="$t('使用情况')">
                <el-select style="width: 100%" clearable v-model="usePage.status">
                  <el-option :value="0" :label="$t('未使用')"></el-option>
                  <el-option :value="1" :label="$t('已使用')"></el-option>
                  <el-option :value="2" :label="$t('已过期')"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('订单编号')">
                <el-input v-model="usePage.orderId"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="$t('APP名称')">
                <el-select style="width: 100%" v-model="usePage.productName" clearable>
                  <el-option v-for="item in productList" :key="item.productId" :label="item.appName"
                             :value="item.productName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: right">
              <el-button type="primary" @click="getCouponConsume">{{ $t('查询') }}</el-button>
              <el-button @click="clearConsumeSearch">{{ $t('重置') }}</el-button>
            </el-col>
          </el-form>
        </el-row>
        <Table border :tableColumn="useDetailsTableColumn" :tableData="useDetailsTableData" :page="usePage"
               @handleSizeChange="useHandleSizeChange"
               @handleCurrentChange="useHandleCurrentChange">
          <template slot="status" slot-scope="{row}">
            {{ row.status === 0 ? $t('未使用') : row.status === 1 ? $t('已使用') : row.status === 2 ? $t('已过期') : $t('未使用') }}
          </template>
        </Table>
      </div>
    </Dialog>
  </div>
</template>

<script>
import {fetchCouponList, couponDetails, couponConsumeList, updateCoupon} from "@/api/marketing";
import AddCoupon from './addCoupon'
import {selectTenant, selectProduct} from "@/api/system";
import {dateFormatSection} from "@/utils/tools";

export default {
  name: "CouponList",
  components: {
    AddCoupon
  },
  data() {
    return {
      tenantList: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableColumn: [
        {label: this.$t("优惠券名称"), prop: 'name', minWidth: 100},
        {label: this.$t("优惠券类型"), prop: 'type', minWidth: 100, slot: 'type'},
        {label: this.$t("发放数量"), prop: 'num', minWidth: 100},
        {label: this.$t("面额"), prop: 'amount', minWidth: 100, slot: 'amount'},
        {label: this.$t("有效天数"), prop: 'validDay', minWidth: 100},
        {label: this.$t("发放对象"), prop: 'sendUser', minWidth: 100, slot: 'sendUser'},
        {label: this.$t("发放APP"), prop: 'sendApp', minWidth: 100, slot: 'sendApp'},
        {label: this.$t("获取方式"), prop: 'getType', minWidth: 100, slot: 'getType'},
        {label: this.$t("是否推送短信"), prop: 'sendSms', minWidth: 100, slot: 'sendSms'},
        {label: this.$t("活动有效期"), prop: 'activityStartTime', minWidth: 200, slot: 'activityTime'},
        {label: this.$t("状态"), prop: 'activityStatus', minWidth: 100, slot: 'activityStatus'},
        {label: this.$t("上架状态"), prop: 'upType', minWidth: 100, slot: 'upType'},
        {label: this.$t("创建时间"), prop: 'createTime', minWidth: 150},
        {label: this.$t("创建人"), prop: 'createName', minWidth: 100},
        {label: this.$t("备注"), prop: 'remark', minWidth: 100},
        {label: this.$t("操作"), slot: 'handle', minWidth: 150, fixed: 'right'},
      ],
      tableData: [],
      sendSmsType: [
        {label: this.$t("游客"), value: 1},
        {label: this.$t("注册未申请"), value: 2},
        {label: this.$t("待还款"), value: 3},
        {label: this.$t("逾期"), value: 4},
        {label: this.$t("结清未复借"), value: 5}
      ],
      couponType: [
        {label: this.$t("利息券"), value: 1},
        {label: this.$t("还款券"), value: 2},
        {label: this.$t("罚息券"), value: 3}
      ],
      couponGetType: [
        {label: this.$t("用户主动领取"), value: 1},
        {label: this.$t("手动定向发放"), value: 2},
        {label: this.$t("系统自动触发发放"), value: 3}
      ],
      detailsTableColumn: [
        {label: this.$t("优惠券名称"), prop: 'name', minWidth: 100},
        {label: this.$t("优惠券类型"), prop: 'type', minWidth: 100, slot: 'type'},
        {label: this.$t("面额"), prop: 'amount', minWidth: 100, slot: 'amount'},
        {label: this.$t("发放对象"), prop: 'sendUser', minWidth: 100, slot: 'sendUser'},
        {label: this.$t("发放APP"), prop: 'sendApp', minWidth: 100, slot: 'sendApp'},
        {label: this.$t("状态"), prop: 'activityStatus', minWidth: 100, slot: 'activityStatus'},
        {label: this.$t("获取方式"), prop: 'getType', minWidth: 100, slot: 'getType'},
        {label: this.$t("有效天数"), prop: 'validDay', minWidth: 100},
        {label: this.$t("发放数量"), prop: 'num', minWidth: 100},
        {label: this.$t("已领取"), prop: 'receiveNum', minWidth: 100},
        {label: this.$t("待领取"), prop: 'notReceiveNum', minWidth: 100},
        {label: this.$t("已使用"), prop: 'useNum', minWidth: 100},
        {label: this.$t("未使用"), prop: 'notUseNum', minWidth: 100},
        {label: this.$t("已过期"), prop: 'dueNum', minWidth: 100},
      ],
      detailsTableData: [],
      couponVisible: {
        isShow: false,
        type: '',
        title: '',
      },
      visibleDetails: false,
      tableRows: {},
      usePage: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      useDetailsTableColumn: [
        {label: this.$t("用户姓名"), prop: 'userName', minWidth: 100},
        {label: this.$t("手机号码"), prop: 'phone', minWidth: 100,},
        {label: this.$t("领取APP"), prop: 'appName', minWidth: 100},
        {label: this.$t("获取时间"), prop: 'getTime', minWidth: 100},
        {label: this.$t("使用情况"), prop: 'status', minWidth: 100, slot: 'status'},
        {label: this.$t("使用时间"), prop: 'useTime', minWidth: 100},
        {label: this.$t("订单编号"), prop: 'orderId', minWidth: 100},
      ],
      useDetailsTableData: [],
      productList: []
    }
  },

  mounted() {
    this.getTableData()
    selectTenant().then(res => {
      this.tenantList = res.data
    })
    selectProduct().then(res => {
      this.productList = res.data
    })
  },
  methods: {
    async getTableData() {
      const [createStartTime, createEndTime] = dateFormatSection(this.page.timeValue)
      const params = {
        ...this.page,
        createStartTime, createEndTime,
      }
      delete params.timeValue
      const res = await fetchCouponList(params)
      if (res.code === 1) {
        const {list, total} = res.data
        this.tableData = list
        this.page.total = total
      }
    },
    resetSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    async couponConfirm() {
      const res = await this.$refs.couponModel.submitForm()
      if (res.code === 1) {
        this.couponVisible.isShow = false
        this.getTableData()
      }
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getTableData()
    },
    couponClose() {
      this.$refs.couponModel.clearForm()
    },
    addCoupon() {
      this.couponVisible = {
        isShow: true,
        type: 'add',
        title: '新增优惠券',
      }
    },
    editCoupon(row) {
      this.tableRows = {...row}
      this.couponVisible = {
        isShow: true,
        type: 'edit',
        title: '编辑优惠券',
      }
    },
    lookDetails(row) {
      this.tableRows = {...row}
      this.couponVisible = {
        isShow: true,
        type: 'details',
        title: '查看优惠券',
      }
    },
    async getCouponDetails(row) {
      this.visibleDetails = true
      this.tableRows = {...row}
      const res = await couponDetails({id: row.id})
      if (res.code === 1) {
        this.detailsTableData = [{...res.data}]
      }
      this.getCouponConsume()
    },
    //  获取优惠券使用情况
    async getCouponConsume() {
      const consumeRes = await couponConsumeList({...this.usePage, couponId: this.tableRows.id})
      if (consumeRes.code === 1) {
        const {list, total} = consumeRes.data
        this.useDetailsTableData = list
        this.usePage.total = total
      }
    },
    clearConsumeSearch() {
      this.usePage = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getCouponConsume()
    },
    useHandleSizeChange(val) {
      this.page.pageSize = val
      this.getCouponConsume()
    },
    useHandleCurrentChange(val) {
      this.page.pageNum = val
      this.getCouponConsume()
    },
    // 上下架
    editUpper(row) {
      this.$confirm(this.$t('确认进行此操作') + '?', this.$t('提示'), {
        type: 'warning'
      }).then(async () => {
        const params = {
          ...row,
          upType: row.upType === 1 ? 2 : 1
        }
        const res = await updateCoupon(params)
        if (res.code === 1) {
          this.$message.success(this.$t('操作成功'))
          this.unBindAppVisible = false
          this.getTableData()
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
